package com.sb.framework.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;

import com.sb.framework.bean.RestStatus;
import com.sb.framework.exception.BusinessException;

public class LogUtil {
	
	private static final String	SEPARATOR	= " ";

	private static final int	DEPTH		= 5;
	
	public static final String getErrorContent(Exception exception, String time) {
		StackTraceElement[] sElements = exception.getStackTrace();
		int depth = sElements.length > DEPTH ? DEPTH : sElements.length;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < depth; i++) {
			String className = sElements[ i ].getClassName();
			String methodName = sElements[ i ].getMethodName();
			int lineNumber = sElements[ i ].getLineNumber();
			String str = String.format( "[%s]%s[%s.%s]%s[%s]", time, SEPARATOR, className, methodName, SEPARATOR, lineNumber );
			if(i==0){
				String code = RestStatus.CODE_500;
				if(exception instanceof BusinessException){
					BusinessException e = (BusinessException) exception;
					code = e.getCode();
				}
				sb.append( str ).append(SEPARATOR).append(String.format("%s[code=%s,message=%s]","SystemErrorException", "500",exception.getMessage()))
				.append(getSystemLineChar());
			}else{
				sb.append( str ).append(getSystemLineChar());
			}
		}
			
		sb.append(getSystemLineChar());
		return sb.toString();
	}
	
	
	private static final String getSystemLineChar() {
		return System.getProperty( "line.separator" );
	}
	
	
	public static void main(String[] args) {
		//System.out.println(System.getProperty( "line.separator" ));
		/*try {
			File f = new File("test/eee");
			
			InputStreamReader isr = new InputStreamReader(new FileInputStream(f));
		} catch (Exception e) {
			
			e.printStackTrace();
			
			String time = DateUtils.formatDate( DATA_FORMAT, new Date() );
			
			System.out.println("**********");
			System.out.println(getErrorContent(e,time));
		}*/
	}
	
}
